/****************************************************
          File Name:12-3_imply.cpp
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Fri 26 Dec 2014 02:26:09 PM CST
*****************************************************/

#include"12-3.h"
#include<cstring>

using std::strcpy;
using std::strlen;
using std::cout;
using std::ostream;

Stock::Stock()
{
    company = new char[8];
    strcpy(company, "no name");
    shares = 0;
    shares_val = 0.0;
    total_val = 0.0;
}

Stock::Stock(const char *co, long n, double pr)
{
    company = new char[strlen(co)];
    strcpy(company, co);

    if(n < 0)
    {
        cout << "Number of shares can't be negative; "
            << company << " shares set to 0.\n";
        shares = 0;
    }
    else
        shares = n;
    shares_val = pr;
    set_tot();
}

Stock::~Stock()
{
    delete [] company;
}

void Stock::buy(long num, double price)
{
    if(num < 0)
    {
        std::cout << "Number of shares purchased can't be negative. "
            << "Transaction is aborted.\n";
    }
    else
    {
        shares += num;
        shares_val = price;
        set_tot();
    }
}

void Stock::sell(long num, double price)
{
    if(num < 0)
    {
        cout << "Number of share sold can't be negative. "
            << "Transaction is aborted\n";
    }
    else if(num > shares)
    {
        cout << "You can't sell more than you have! "
            << "Transaction is aborted\n";
    }
    else
    {
        shares -= num;
        shares_val = price;
        set_tot();
    }
}

void Stock::update(double price)
{
    shares_val = price;
    set_tot();
}

ostream & operator<<(ostream & os, const Stock & s)
{
    using std::ios_base;
    ios_base::fmtflags orig = cout.setf(ios_base::fixed, ios_base::floatfield);
    std::streamsize prec = cout.precision(3);

    os << "Company: " << s.company << " Shares: " << s.shares << '\n';
    os << " Shares Price: $" << s.shares_val;
    cout.precision(2);
    os << " Total Worth: $" << s.total_val << '\n';

    return os;
}

const Stock & Stock::topval(const Stock & s) const
{
    if(s.total_val > total_val)
        return s;
    else
        return *this;
}
